package com.example.fechat.room.user

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase

@Database(entities = [UserEntity::class], version = 1, exportSchema = false)
abstract class UserDatabase : RoomDatabase() {
    abstract val userDao: UserDao?

    companion object {
        @Volatile
        private var instance: UserDatabase? = null

        @JvmStatic
        fun getDatabase(context: Context): UserDatabase? {
            if (instance == null) {
                synchronized(UserDatabase::class.java) {
                    if (instance == null) {
                        instance = Room.databaseBuilder(
                            context.applicationContext,
                            UserDatabase::class.java, "user_database"
                        )
                            .addCallback(object : Callback() {
                                override fun onCreate(db: SupportSQLiteDatabase) {
                                    super.onCreate(db)
                                }
                                override fun onOpen(db: SupportSQLiteDatabase) {
                                    super.onOpen(db)
                                }
                            })
                            .fallbackToDestructiveMigration() // 数据库版本升级，数据迁移(本项目删除并重新创建整个数据库，因为每次在首页获取设备信息，直接保存)
                            .allowMainThreadQueries() //允许在主线程查询数据
                            .build()
                    }
                }
            }
            return instance
        }

        fun onDestroy() {
            instance = null
        }
    }
}